package com.hoo.servlet;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import com.hoo.common.constant.Constant;
import com.hoo.entity.equipment.Advertise;
import com.hoo.entity.equipment.InvoiceRule;
import com.hoo.service.account.VisitorService;
import com.hoo.service.equipment.AdvertiseService;
import com.hoo.service.equipment.InvoiceMachineService;
import com.hoo.service.order.TicketOrderService;
import com.hoo.util.Base64;

public class SSocket implements Runnable {

    private boolean connected = false;  
    private Socket client = null;  
    private DataInputStream input = null;  
    private DataOutputStream output = null;
    private int count = 0;
    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
	VisitorService visitorService = (VisitorService)wac.getBean("visitorService");
	TicketOrderService ticketOrderService = (TicketOrderService)wac.getBean("ticketOrderService");
	InvoiceMachineService invoiceMachineService = (InvoiceMachineService)wac.getBean("invoiceMachineService");
	AdvertiseService advertiseService=(AdvertiseService)wac.getBean("advertiseService");
	
    public SSocket(Socket client, boolean connected) {  
        this.client = client;  
        this.connected = connected;   
        Map<String,Object> map=new HashMap<String, Object>();
		map.put("connectStatus",Constant.CONNECT_STATUS_SUCCESS);
		map.put("ip", client.getInetAddress().getHostAddress());
		invoiceMachineService.updateInvoiceMachineConnectStatusByIP(map);
    }   
    public void run() {
		try {
			if(connected){
				input = new DataInputStream(client.getInputStream());
				output = new DataOutputStream(client.getOutputStream());
			}
			while (connected) {
				count++;
				System.err.println(count);
				try {
					String receive = Base64.desDecrypt(input.readUTF(), Base64.KEY);
					//判断客户端发送来的字符串中是否含有标识字符串“checkschedulenum”，若含有，则进行检查预约号，否则进行游客信息插入
					if(receive.startsWith(Constant.defaultTakeTicketByIDcardPrefix)){//身份证取票操作
						output.writeUTF(visitorService.handleInsertVisitorEvent(receive.substring(Constant.defaultTakeTicketByIDcardPrefix.length())));	
					}else if(receive.startsWith(Constant.defaultTakeTicketByScheduleNum)){//预约号取票
						output.writeUTF(ticketOrderService.handleTicketByScheduleNum(Constant.ticketNo,receive.substring("checkschedulenum".length())));
						
						/*TicketOrder order = ticketOrderService.getTicketOrderBySchedule(receive.substring("checkschedulenum".length()));
						if(null != order){
							if(1 != order.getTakeOrderStatus()){
								SimpleDateFormat simpleDateFormat=new SimpleDateFormat(Constant.DATE_FORMAT_SIMPLE);
								long date1 = simpleDateFormat.parse(simpleDateFormat.format(new Date())).getTime();
								long date2 = simpleDateFormat.parse(simpleDateFormat.format(order.getVisitTime())).getTime();
								if(date1>=date2){
									Map<String, Object> map=new HashMap<String, Object>();
									map.put("name", order.getLinkmanName());
									map.put("ticketCount", String.valueOf(order.getTicketCount()));
									map.put("scheduleNum",receive.substring("checkschedulenum".length()));
									map.put("visitTime", simpleDateFormat.format(order.getVisitTime()));
									order.setTakeOrderTime(new Date());
									order.setTakeOrderStatus(1);//已经取票
									//ticketOrderService.updateTicketOrder(order);//修改取票时间
									ticketOrderService.handleTicketByScheduleNum(order, Constant.ticketNo);
									output.writeUTF(Base64.desEncrypt(JSONObject.fromObject(map).toString(), Base64.KEY));
								}else{
									output.writeUTF(Constant.OVERDUE);//预约时间已过
								}
							}else {
								output.writeUTF(Constant.DELIVERED);//该预约号已经取过
							}
						}else {
							output.writeUTF(Constant.NO_ORDER);//未查到此订单信息
						}*/
						
					}else if(receive.startsWith(Constant.defaultRequestResource)){ //请求获取资源
						ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
						List<Advertise> advertises = advertiseService.getAdvertiseListByMachineIp(client.getInetAddress().getHostAddress());
						InvoiceRule invoiceRule = invoiceMachineService.getInvoiceRule();
						List<Object> advertiseAndListInvoiceRule =new ArrayList<Object>();
						advertiseAndListInvoiceRule.add(advertises);
						advertiseAndListInvoiceRule.add(invoiceRule);
						output.writeObject(advertiseAndListInvoiceRule);
					}
				} catch (Exception e) {
					output.writeUTF(Constant.FAIL); //系统处理异常
				}
				output.flush();
			}
		} catch (IOException e) {
			try {
				Map<String,Object> map=new HashMap<String, Object>();
				map.put("connectStatus", Constant.CONNECT_STATUS_FAIL);
				map.put("ip", client.getInetAddress().getHostAddress());
				invoiceMachineService.updateInvoiceMachineConnectStatusByIP(map);
				client.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}finally{
				e.printStackTrace();
				connected=false;
			}
		}
	}
}

